#Alexander F. Gazmararian
#afg2@princeton.edu

library(tidyverse)
library(modelsummary)
library(lmtest)
library(sandwich)
library(kableExtra)
library(margins)

source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/fix_txt.r")
source("code/fun/coefnames4tables.r")

# Load CivicPulse data
cp <- readRDS("data/CivicPulse_Public.rds")

# Load national sample
caps <- readRDS("data/NatCAPS_20220816.rds")
caps <- rename(caps, income = Income_long) # Rename income column

# Merge and prepare data ----
caps_biz <- subset(caps, select = c(BizPred:BizPay, sample, nweightNL33D_NEW2))
cp_biz <- subset(cp, select = c(BizPred:BizPay, Sample, Weight_1))
caps_biz <- caps_biz %>% rename(weights = nweightNL33D_NEW2)
cp_biz <- cp_biz %>% rename(weights = Weight_1, sample = Sample)
biz <- rbind(caps_biz, cp_biz)

# Prepare data for analysis
biz <-
  biz %>%
  pivot_longer(cols = c(BizPred:BizPay))
biz <-
  biz %>%
  mutate(
    sampleSlim = dplyr::case_when(
      sample %in% c("Standard", "Targeted") ~ "Policymakers",
      sample == "CAPS" ~ "National"
    ),
    sample = dplyr::case_when(
      sample == "CAPS" ~ "National",
      sample == "Standard" ~ "Policymakers (National)",
      sample == "Targeted" ~ "Policymakers (Fossil Fuel)"
    )
  )

# Create Figure 3.8 (Government Commitment)

commit.plot <-
  biz %>%
  filter(name == "BizPred" & !is.na(value)) %>%
  group_by(value, sample) %>%
  summarise(n = sum(weights)) %>%
  group_by(sample) %>%
  mutate(pct = prop.table(n)) %>%
  ggplot(aes(x=value,y=pct,fill=sample,label=scales::percent(pct, accuracy = 1))) +
  geom_col(position="dodge") +
  geom_text(position = position_dodge(.9), vjust = -.5, size = 3) +
  scale_y_continuous(labels = scales::percent, expand = c(0,0), limits = c(0,.45)) +
  scale_x_discrete(labels = scales::label_wrap(25)) +
  scale_fill_grey(name = "") +
  labs(y="",x="Would political support at the federal level decrease in the future?") +
  book_theme +
  theme(
    legend.position = "bottom",
    legend.box.margin = margin(-10)
  )
commit.plot
savefig(commit.plot, "3.8_figure_bizuncertain", height = 2, filepath = "figures/")  
